package cn.edu.scnu.controller;

import cn.edu.scnu.common.MD5Util;
import cn.edu.scnu.entity.Admin;
import cn.edu.scnu.entity.Myorder;
import cn.edu.scnu.entity.Showorder;
import cn.edu.scnu.service.AdminService;
import cn.edu.scnu.service.FlowerService;
import cn.edu.scnu.service.OrderSevice;
import cn.edu.scnu.service.ShoworderService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpSession;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@Controller
public class AdminController {
    @Resource
    private AdminService adminService;
    @Resource
    private FlowerService flowerService;
    @Resource
    private OrderSevice orderService;
    @Resource
    private ShoworderService showorderService;

    @RequestMapping("/admin")
    public String admin(HttpSession session) {
        if (session.getAttribute("admin") == null) {

            return "redirect:/admin/toAdminLogin";
        }
        return "adminindex";
    }
    @RequestMapping("/admin/adminindex")
    public String adminindex(HttpSession session) {
        if (session.getAttribute("admin") == null) {

            return "redirect:/admin/toAdminLogin";
        }
        return "adminindex";
    }
    @RequestMapping("/admin/toAdminLogin")
    public String toAdminLogin(){
       return "adminlogin";
    }
    // 后台登录
    @RequestMapping("/admin/doAdminLogin")
    @ResponseBody
    public String doAdminLogin(String username, String password, HttpSession session) {
        Admin admin = adminService.getById(username);

        if (admin != null && admin.getPassword().equals(MD5Util.md5(password))) {
            admin.setPassword("");
            session.setAttribute("admin", admin);
            return "登录成功";
        } else {
            return "登录失败";
        }
    }
    @RequestMapping("/admin/orderlist")
    public String orderList(String status, Model model, HttpSession session){
        Admin admin = (Admin)session.getAttribute("admin");
        if(admin == null){
            return "redirect:/admin/toAdminLogin";
        }
        if(admin.getAuthority().equals("1") || admin.getAuthority().equals("3")){
            List<Showorder> showorders = showorderService.orderList(status);
            model.addAttribute("showorders", showorders);
            return "adminshoworder";
        }
        return "redirect:/admin/toAdminLogin";
    }
    // 发货功能
    @RequestMapping("/admin/send")
    public String send(Integer id){
        Myorder myorder = orderService.getById(id);
        myorder.setStatus("已发货");
        orderService.updateById(myorder);
        return "forward:/admin/orderlist";
    }
}
